import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { Result, Button } from 'antd';
import { usePlatformStore } from '../../stores/platform';
import { usePlatformPermission } from '../../hooks/platform/usePlatformPermission';

interface PlatformPermissionGuardProps {
  children: React.ReactNode;
  requiredPermissions?: string[];
  requiredRoles?: string[];
  fallback?: React.ReactNode;
  skipInDev?: boolean;
}

const PlatformPermissionGuard: React.FC<PlatformPermissionGuardProps> = ({
  children,
  requiredPermissions = [],
  requiredRoles = [],
  fallback,
  skipInDev = true,
}) => {
  const { isAuthenticated, user } = usePlatformStore();
  const { checkPermission, checkAnyRole, isSuperAdmin } = usePlatformPermission();
  const location = useLocation();

  const isDevelopment = import.meta.env.DEV;
  
  // 开发环境跳过权限检查
  if (isDevelopment && skipInDev) {
    return <>{children}</>;
  }

  // 未认证用户重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/platform/login" state={{ from: location }} replace />;
  }

  // 超级管理员拥有所有权限
  if (isSuperAdmin) {
    return <>{children}</>;
  }

  // 检查角色权限
  if (requiredRoles.length > 0) {
    const hasRequiredRole = checkAnyRole(requiredRoles);
    if (!hasRequiredRole) {
      if (isDevelopment) {
        console.warn('⚠️ 平台权限检查失败：缺少角色权限', {
          required: requiredRoles,
          current: user?.roleIds?.split(',') || [],
          path: location.pathname
        });
      }
      
      return fallback || (
        <Result
          status="403"
          title="403"
          subTitle={
            isDevelopment 
              ? `开发环境：缺少角色权限 [${requiredRoles.join(', ')}]，当前角色：[${user?.roleIds || '无'}]`
              : "抱歉，您没有权限访问此页面。"
          }
          extra={
            <div>
              <Button type="primary" onClick={() => window.history.back()}>
                返回上页
              </Button>
              {isDevelopment && (
                <Button 
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    console.log('当前用户信息：', user);
                    console.log('需要的角色：', requiredRoles);
                  }}
                >
                  查看权限信息
                </Button>
              )}
            </div>
          }
        />
      );
    }
  }

  // 检查具体权限
  if (requiredPermissions.length > 0) {
    const hasRequiredPermission = requiredPermissions.some(permission => 
      checkPermission(permission)
    );
    
    if (!hasRequiredPermission) {
      if (isDevelopment) {
        console.warn('⚠️ 平台权限检查失败：缺少具体权限', {
          required: requiredPermissions,
          path: location.pathname,
          user: user?.username
        });
      }
      
      return fallback || (
        <Result
          status="403"
          title="403"
          subTitle={
            isDevelopment 
              ? `开发环境：缺少权限 [${requiredPermissions.join(', ')}]`
              : "抱歉，您没有权限访问此功能。"
          }
          extra={
            <div>
              <Button type="primary" onClick={() => window.history.back()}>
                返回上页
              </Button>
              {isDevelopment && (
                <Button 
                  style={{ marginLeft: 8 }}
                  onClick={() => {
                    console.log('当前用户信息：', user);
                    console.log('需要的权限：', requiredPermissions);
                  }}
                >
                  查看权限信息
                </Button>
              )}
            </div>
          }
        />
      );
    }
  }

  return <>{children}</>;
};

export default PlatformPermissionGuard;